#-*- coding:utf-8 -*-

import re
import os
from conf import tomcatInfo_dir

class GetTomcatMessage(object):
    def __project_port__(self):
        port_data = {}
        num = 1
        for line in os.popen('netstat -tpnl'):
            if num > 2:
                line_list = line.split()
                port = line_list[6][:line_list[6].find('/')]
                if not port in port_data.keys():
                    port_data[port] = []
                try:
                    PORT = line_list[3].split()[0]
                    port_data[port].append(PORT.split(":")[len(PORT.split(":")) - 1])
                except Exception as error:
                    print error
            num += 1
        return port_data

    def __project_deploy__(self,tomcat_dir):
        project_data = []
        for project in os.popen('ls %s' % tomcat_dir):
            if not project.strip() in ['tomcat_log', 'backup', 'lost+found']:
                project_data.append(project.strip())
        return project_data

    def __project_run__(self):
        project_data = []
        project_name = []
        port_data = self.__project_port__()
        for project in os.popen('ps -ef | grep tomcat'):
            line = re.split('/| *', project)
            try:
                if re.match('-Djava.*', line[21]):
                    line.pop(21)
                if re.match('-server', line[21]):
                    line.pop(21)
                if len(line) > 25:
                    memory_config = []
                    for num in range(21,len(line)-1):
                        if re.match('^-X.*',line[num]):
                            memory_config.append(line[num])
                        else:
                            break
                    id_user = os.popen('id %s' % line[17]).read().strip().split()
                    user = id_user[0].split("=")[1]
                    user = user[:user.find("(")]
                    group = id_user[1].split("=")[1]
                    group = user[:group.find("(")]
                    project_data.append({'project':line[17],
                                         'pid': line[1],
                                         'user':user,
                                         'group':group,
                                         'memory_config': memory_config,
                                         'port': port_data[line[1]]})
                    project_name.append(line[17])
            except IndexError:
                pass
        return project_data,project_name

    def tomcat_data(self):
        depolay_project =  self.__project_deploy__(tomcatInfo_dir)
        run_project,run_list = self.__project_run__()
        diff_list = list(set(depolay_project).difference(run_list))
        for name in diff_list:
            run_project.append({'project':name,'memory_config':[],'pid':'','port':[],'user':'','group':''})
        return run_project